<?php

/**
 * Object layer for mcrypt encrypt and decrypt
 * @author David Safranek <safrad@email.cz>
 */
class SxCrypt {

	/**
	 *
	 * @var string
	 */
	private $password = '';
	
	/**
	 *
	 * @var string
	 */
	private $salt = '!kQm*fF3apXe1wKbm%9';
	
	/**
	 * SHA256 hash of $salt and $password
	 * @var string
	 */
	private $key = '';
	
	function __construct() {
		$this->setKey();
	}
	
	private function setKey() {
		// Build a 256-bit $key which is a SHA256 hash of $salt and $password.
		$this->key = hash('SHA256', $this->salt . $this->password, true);
	}

	public function getPassword() {
		return $this->password;
	}

	public function getSalt() {
		return $this->salt;
	}

	public function getKey() {
		return $this->key;
	}

	public function setPassword($password) {
		$this->password = $password;
		$this->setKey();
	}

	public function setSalt($salt) {
		$this->salt = $salt;
		$this->setKey();
	}

	const iv_base64 = 22;
	
	function encrypt($decrypted) { 
		// Build $iv and $iv_base64.  We use a block size of 128 bits (AES compliant) and CBC mode.  (Note: ECB mode is inadequate as IV is not used.)
		srand(); $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
		if (strlen($iv_base64 = rtrim(base64_encode($iv), '=')) != self::iv_base64) {
			return false;
		}
		// Encrypt $decrypted and an MD5 of $decrypted using $key.  MD5 is fine to use here because it's just to verify successful decryption.
		$encryptedWidthHash = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->getKey(), $decrypted . md5($decrypted), MCRYPT_MODE_CBC, $iv));
		// We're done!
		return $iv_base64 . $encryptedWidthHash;
	}

	function decrypt($encrypted) {
		// Retrieve $iv which is the first 22 characters plus ==, base64_decoded.
		$iv = base64_decode(substr($encrypted, 0, self::iv_base64) . '==');
		// Remove $iv from $encrypted.
		$encrypted = substr($encrypted, self::iv_base64);
		// Decrypt the data.  rtrim won't corrupt the data because the last 32 characters are the md5 hash; thus any \0 character has to be padding.
		$decryptedWithHash = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->getKey(), base64_decode($encrypted), MCRYPT_MODE_CBC, $iv), "\0\4");
		// Retrieve $hash which is the last 32 characters of $decrypted.
		$hash = substr($decryptedWithHash, -32);
		// Remove the last 32 characters from $decrypted.
		$decrypted = substr($decryptedWithHash, 0, -32);
		// Integrity check.  If this fails, either the data is corrupted, or the password/salt was incorrect.
		if (md5($decrypted) != $hash) {
			return false;
		}
		// Yay!
		return $decrypted;
	}
}